<template>
  <div class="mobile-detail">
    <!-- 顶部导航栏 -->
    <div class="mobile-nav-bar">
      <el-icon @click="goBack">
        <ArrowLeft />
      </el-icon>
      <span class="nav-title">电影详情</span>
      <div class="placeholder"></div>
    </div>

    <!-- 电影信息 -->
    <div class="movie-info" v-if="movieDetail">
      <div
        class="movie-header"
        :style="{ backgroundImage: `url(${movieDetail.photo})` }"
      >
        <div class="movie-header-content">
          <img :src="movieDetail.photo" alt="电影海报" class="movie-poster" />
          <div class="movie-basic-info">
            <h1 class="movie-title">{{ movieDetail.name }}</h1>
            <div class="movie-score">{{ movieDetail.rating }}分</div>
            <div class="movie-meta">类型：{{ movieDetail.type }}</div>
            <div class="movie-meta">导演：{{ movieDetail.director }}</div>
            <div class="movie-meta">时长：{{ movieDetail.movieLength }}分钟</div>
          </div>
        </div>
      </div>

      <!-- 电影简介 -->
      <div class="movie-section">
        <h2 class="section-title">剧情简介</h2>
        <p class="movie-intro">{{ movieDetail.intro }}</p>
      </div>

      <!-- 放映场次 -->
      <div class="movie-section">
        <h2 class="section-title">放映场次</h2>
        <div class="show-times" v-if="showTimes.length > 0">
          <div
            v-for="item in showTimes"
            :key="item.id"
            class="show-time-item"
            @click="selectShowTime(item.id,movieDetail.id)"
          >
            <div class="show-time-info">
              <div class="show-time">{{ formatTime(item.time) }}</div>
              <div class="show-hall">{{ item.name }}</div>
              <div class="show-price">¥{{ movieDetail.price }}</div>
            </div>
            <el-button type="danger" size="small">选座购票</el-button>
          </div>
        </div>
        <el-empty v-else description="暂无放映场次" />
      </div>

      <!-- 电影评论 -->
      <div class="movie-section">
        <h2 class="section-title">观众评论</h2>
        <div class="reviews" v-if="reviews.length > 0">
          <div v-for="review in reviews" :key="review.id" class="review-item">
            <div class="review-header">
              <div class="reviewer-info">
                <el-avatar
                  :size="32"
                  :src="
                    review.avatar ||
                    'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'
                  "
                ></el-avatar>
                <span class="reviewer-name">{{ review.userName }}</span>
              </div>
              <div class="review-score">
                <el-rate v-model="review.rating" disabled text-color="#ff9900" />
              </div>
            </div>
            <div class="review-content">{{ review.content }}</div>
            <div class="review-footer">
              <span class="review-time">
                {{ formatTime(review.createTime) }}
              </span>
              <div class="review-like" @click="likeReview(review.id)">
                <el-icon>
                  <ThumbUp />
                </el-icon>
                <span>{{ review.likes || 0 }}</span>
              </div>
            </div>
          </div>
        </div>
        <el-empty v-else description="暂无观众评论" />
        <!-- 添加评论 -->
        <div class="add-review">
          <h3 class="add-review-title">添加评论</h3>
          <el-form :model="reviewForm" :rules="reviewRules" ref="reviewFormRef">
            <el-form-item prop="score">
              <el-rate v-model="reviewForm.score" />
            </el-form-item>
            <el-form-item prop="content">
              <el-input
                v-model="reviewForm.content"
                type="textarea"
                :rows="3"
                placeholder="分享您的观影体验..."
              />
            </el-form-item>
            <el-form-item>
              <el-button
                type="primary"
                @click="submitReview"
                :loading="submitting"
              >
                提交评论
              </el-button>
            </el-form-item>
          </el-form>
        </div>
      </div>
    </div>

    <!-- 加载中 -->
    <div v-else class="loading-container">
      <el-skeleton :rows="10" animated />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive } from "vue";
import { useRoute, useRouter } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import { ArrowLeft } from "@element-plus/icons-vue";
import {
  mobileReqFilmDetail,
  mobileReqFilmShow,
  mobileGetAllReviews,
  mobileAddReview,
  mobileLikeReview
} from "@/api/mobile";

const route = useRoute();
const router = useRouter();
const movieId = ref(Number(route.params.id));
const movieDetail = ref(null);
const showTimes = ref([]);
const reviews = ref([]);
const reviewFormRef = ref();
const submitting = ref(false);

// 返回上一页
const goBack = () => {
  router.back();
};

// 获取电影详情
const getMovieDetail = async () => {
  try {
    const result = await mobileReqFilmDetail(movieId.value);
    if (result.code === 200) {
      movieDetail.value = result.data;
    } else {
      ElMessage.error(result.message || "获取电影详情失败");
    }
  } catch (error) {
    console.error("获取电影详情出错", error);
    ElMessage.error("获取电影详情失败");
  }
};

// 获取放映场次
const getShowTimes = async () => {
  try {
    const result = await mobileReqFilmShow(movieId.value);
    if (result.code === 200) {
      showTimes.value = result.data || [];
    } else {
      ElMessage.error(result.message || "获取放映场次失败");
    }
  } catch (error) {
    console.error("获取放映场次出错", error);
    ElMessage.error("获取放映场次失败");
  }
};

// 获取电影评论
const getReviews = async () => {
  try {
    const result = await mobileGetAllReviews(movieId.value);
    if (result.code === 200) {
      reviews.value = result.data || [];
    } else {
      ElMessage.error(result.message || "获取电影评论失败");
    }
  } catch (error) {
    console.error("获取电影评论出错", error);
    ElMessage.error("获取电影评论失败");
  }
};

// 选择场次
const selectShowTime = (showId, movieId) => {
  ElMessageBox.confirm("确定选择此场次进行购票吗？", "选座购票", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  })
    .then(() => {
      // 跳转到选座页面，这里简化处理
      ElMessage.success("即将跳转到选座页面");
      router.push(`/mobile/seat/${showId}/${movieId}`);
    })
    .catch(() => {
    });
};

// 评论表单
const reviewForm = reactive({
  score: 5,
  content: ""
});

// 评论表单验证规则
const reviewRules = {
  score: [{ required: true, message: "请选择评分", trigger: "change" }],
  content: [
    { required: true, message: "请输入评论内容", trigger: "blur" },
    {
      min: 5,
      max: 200,
      message: "评论内容长度应为5-200个字符",
      trigger: "blur"
    }
  ]
};

// 提交评论
const submitReview = async () => {
  if (!reviewFormRef.value) return;
  await reviewFormRef.value.validate(async (valid) => {
    if (valid) {
      submitting.value = true;
      try {
        const result = await mobileAddReview({
          movieId: movieId.value,
          userId: localStorage.getItem("id"),
          content: reviewForm.content,
          rating: reviewForm.score
        });

        if (result.code === 1) {
          ElMessage.success("评论提交成功");
          reviewForm.content = "";
          // 重新获取评论列表
          await getReviews();
        } else {
          ElMessage.error(result.message || "评论提交失败");
        }
      } catch (error) {
        console.error("提交评论出错", error);
        ElMessage.error("评论提交失败");
      } finally {
        submitting.value = false;
      }
    }
  });
};

// 点赞评论
const likeReview = async (reviewId) => {
  try {
    const result = await mobileLikeReview(reviewId);
    if (result.code === 1) {
      ElMessage.success("点赞成功");
      // 更新评论列表中的点赞数
      await getReviews();
    } else {
      ElMessage.error(result.message || "点赞失败");
    }
  } catch (error) {
    console.error("点赞评论出错", error);
    ElMessage.error("点赞失败");
  }
};

// 格式化时间
const formatTime = (timeStr) => {
  return timeStr[0] + "年" + timeStr[1] + "月" + timeStr[2] + "日";
};

onMounted(() => {
  getMovieDetail();
  getShowTimes();
  getReviews();
});
</script>

<style scoped lang="scss">
.mobile-detail {
  min-height: 100vh;
  background-color: #f5f7fa;
  padding-bottom: 60px;
}

.mobile-nav-bar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px 15px;
  background-color: #fff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  position: sticky;
  top: 0;
  z-index: 10;

  .el-icon {
    font-size: 20px;
    cursor: pointer;
  }

  .nav-title {
    font-size: 18px;
    font-weight: bold;
  }

  .placeholder {
    width: 20px;
  }
}

.movie-header {
  position: relative;
  padding: 20px 15px;
  background-size: cover;
  background-position: center;
  color: #fff;

  &::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: linear-gradient(
        to bottom,
        rgba(0, 0, 0, 0.7) 0%,
        rgba(0, 0, 0, 0.5) 100%
    );
    z-index: 1;
  }

  .movie-header-content {
    position: relative;
    z-index: 2;
    display: flex;
    gap: 15px;
  }

  .movie-poster {
    width: 120px;
    height: 180px;
    border-radius: 8px;
    object-fit: cover;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
  }

  .movie-basic-info {
    flex: 1;
    display: flex;
    flex-direction: column;
    justify-content: center;

    .movie-title {
      font-size: 20px;
      margin: 0 0 10px;
    }

    .movie-score {
      font-size: 18px;
      font-weight: bold;
      color: #ffcc00;
      margin-bottom: 10px;
    }

    .movie-meta {
      font-size: 14px;
      margin-bottom: 5px;
      opacity: 0.9;
    }
  }
}

.movie-section {
  background-color: #fff;
  margin: 10px 0;
  padding: 15px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);

  .section-title {
    font-size: 18px;
    margin: 0 0 15px;
    padding-bottom: 10px;
    border-bottom: 1px solid #eee;
  }

  .movie-intro {
    font-size: 14px;
    line-height: 1.6;
    color: #606266;
    text-align: justify;
  }
}

.show-times {
  display: flex;
  flex-direction: column;
  gap: 10px;

  .show-time-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 12px;
    border-radius: 8px;
    background-color: #f9f9f9;

    .show-time-info {
      display: flex;
      flex-direction: column;
      gap: 5px;
    }

    .show-time {
      font-size: 16px;
      font-weight: bold;
    }

    .show-hall,
    .show-price {
      font-size: 14px;
      color: #606266;
    }

    .show-price {
      color: #ff6b6b;
      font-weight: bold;
    }
  }
}

.reviews {
  display: flex;
  flex-direction: column;
  gap: 15px;

  .review-item {
    padding: 12px;
    border-radius: 8px;
    background-color: #f9f9f9;
  }

  .review-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 10px;

    .reviewer-info {
      display: flex;
      align-items: center;
      gap: 8px;

      .reviewer-name {
        font-size: 14px;
        font-weight: bold;
      }
    }
  }

  .review-content {
    font-size: 14px;
    line-height: 1.6;
    color: #303133;
    margin-bottom: 10px;
  }

  .review-footer {
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-size: 12px;
    color: #909399;

    .review-like {
      display: flex;
      align-items: center;
      gap: 5px;
      cursor: pointer;

      &:hover {
        color: #ff6b6b;
      }
    }
  }
}

.add-review {
  margin-top: 20px;
  padding-top: 15px;
  border-top: 1px dashed #eee;

  .add-review-title {
    font-size: 16px;
    margin-bottom: 15px;
  }
}

.loading-container {
  padding: 20px 15px;
}
</style>
